<?php
    
    // models
    use_model('file_folders','file_types');

    class Files extends ActiveRecord {
        
        var $allowed_types      = array();
        var $disallowed_types   = array();
        // if you are using this class to deal with files that 
        // have been added to the system without uploading them, 
        // set this to false. by default this class looks for $_FILES
        var $is_file_upload     = true; 
        
        var $file_filters = array(
                                 'all' => 'all',
                                 'image' => 'image',
                                 'application' => 'application',
                                 'text' => 'text',
                                 );
        
        function _setup()
        {
            $this->table = DB_PREFIX.'files';
            
            // set upload max
            $max_upload = trim( ini_get('upload_max_filesize') );            
            $delimiter = strtolower( substr($max_upload, -1 , 1) );
            switch ( $delimiter )
            {
                case 'g':
                    $max_upload *= 1024;
                case 'm':
                    $max_upload *= 1024;
                case 'k':
                   $max_upload *= 1024;
            }
            
            define('MAX_FILE_SIZE', $max_upload); // this is ~
        }        
            
        function validate()
        {
            $this->is_valid_file();
        }
        
        function before_validation_on_create()
        {
            $this->add_file();
        }
        
        // match mime and file extention
        function is_valid_file()
        {
            $this->get_file_types();
            $is_valid = false;
            foreach( $this->allowed_types as $type )
            {                
                $ext = strtolower(substr($this->fields['name'], strrpos($this->fields['name'], '.') + 1));
                if ( strcasecmp($this->fields['type'], $type['mime']) == 0 
                     &&  strcasecmp($ext,$type['ext']) == 0 )
                {
                    $is_valid = true;
                    break;
                }
            }
            if ( !$is_valid )
            {
                $this->add_error('File', 'File type not allowed on server.');
            }
            return $is_valid;
        }
        
        function get_file_types()
        {
            $file_types = new File_Types();
            $this->allowed_types = $file_types->get_allowed_types();
        }
        
        function add_file()
        {
            if ( !$this->is_file_upload )
            {
                return;
            }
            use_pixel_lib('class.upload.php');
            $file =& Upload::getFile('name');
            if (!$file) {                
                $this->add_error('File','Failed to transfer file.');
                return;
            }
            // check file size first
            if ( $file->checkSize(MAX_FILE_SIZE) )
            {
                // safe name the file
                $file->nameToSafe();
                
                $this->set('name', $file->name) ;
                $this->set('type', $file->type) ;
                $this->set('ext',  $file->ext) ;
                $this->set('size', $file->size) ;
                $this->set('created',DB_DATESTAMP);
                $this->set('last_modified',DB_DATESTAMP);
                // check that file name is valid
                if(!$this->is_valid_file()) 
                {
                    $this->unload();
                    return false;
                }
                
                $folders     =& new File_Folders();
                $upload_path = $folders->get_server_path($this->get('file_folder_id'));
                if ( !$file->moveTo($upload_path,false) ) // don't overwrite a file that already exists
                {                    
                    $this->add_error('File','Upload failed: '.$file->getError());
                }
            } else {
                $this->add_error('File','Your file exceeds the max of: '.string_format_file_size(MAX_FILE_SIZE));
            }
        }        
        
        function delete_file($id)
        {
            $this->load($id);
            if($this->is_loaded()){
                $folders = new File_Folders();
                $path = $folders->get_server_path($this->get('file_folder_id'));
                $filepath = $path.'/'.$this->get('name');
                if(file_exists($filepath)){
                    @unlink($filepath);                
                    if($this->delete()) $this->unload();
                    return true;
                } else { // file doesnt really exist, so kill from db anyways                
                    if($this->delete()) $this->unload();
                    return true;
                }
            } else {
                trigger_error('Can not delete file, no id loaded.',WARNING);
            }      
            return false;
        }
               
        function get_files_by_folder($id, $filter = 'all')
        {
            $where = '';
            if ( $filter != 'all' )
            {
                $where = " AND type LIKE '{$this->file_filters[$filter]}/%'";
            }
            return $this->find_rows( array('conditions'=>array("file_folder_id=? $where",$id), 'order'=>'name' ));
        }

		function get_files_by_folder_and_image_type($id, $img_type=null)
        {
			if ( is_null($img_type) )
			{
				$where = " AND type LIKE 'image/jp%'";
			} else {
				$where = " AND type LIKE 'image/$img_type'";
			}
            return $this->find_rows( array('conditions'=>array("file_folder_id=? $where",$id), 'order'=>'name' ));
        }
        
        function get_filters()
        {
            return $this->file_filters;
        }
        
        function crop_image($options)
        {   
            // jpg fix
            $mime_type = $this->get('type');
            $jpegs = array('image/jpeg','image/jpg','image/pjpeg');
            if(in_array($mime_type, $jpegs)){
                $mime_type = 'image/jpeg';   
            }
             
            // path to file will return with a / in the front fyi
            $file_folders = new File_Folders();
            $path_to_file = path_to_file($this->get('file_folder_id'));  
            $server_path_to_file = $file_folders->get_server_path($this->get('file_folder_id'));
            
            // create php thumb instance and get jiggy with it.
            require VENDOR .'/phpthumb/phpthumb.class.php';
            $phpThumb = new phpThumb();
            $phpThumb->setSourceFilename($server_path_to_file.'/'.$this->get('name'));
        
            // set output type
            $phpThumb->config_output_format = str_replace('image/','',$mime_type);
            $phpThumb->sx = (int) $options['x1'];
            $phpThumb->sy = (int) $options['y1'];
            $phpThumb->sw = (int) $options['c_width'];
            $phpThumb->sh = (int) $options['c_height'];
            $newW         = (int) $options['c_width'];
            $newH         = (int) $options['c_height'];
            $file_name_action = 'crop';

            // save file as a new file, then input into db
            if(isset($options['save_as_new'])){                                        
                // create a new filename
                $ext         = $this->get('ext');
                $rawname     = strtolower(substr($this->get('name'), 0, strrpos($this->get('name'), '.')));
                $rawname     = preg_replace('/[^\w.-]/', '_',$rawname); // make safe
                $uniqid      = uniqid("_{$newW}x{$newH}_");
                $newfilename = "{$rawname}_{$file_name_action}{$uniqid}.{$ext}";                    
                if ($phpThumb->GenerateThumbnail()) {
                    if (!$phpThumb->RenderToFile($server_path_to_file.'/'.$newfilename)) {
                        error_log(print_r($phpThumb->debugmessages,1));
                        flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                        return;
                    }
                } else {
                    error_log(print_r($phpThumb->debugmessages,1));
                    flash('error','There was a fatal error in the image processing, please view the error logs for the output');
                    return;
                }
                @chmod($server_path_to_file.'/'.$newfilename, 0755);
            
                // insert into db 
                $new_file = new Files();
                $new_file->is_file_upload = false;
                $new_file->set('name', $newfilename);
                $new_file->set('size', filesize($server_path_to_file . '/'. $newfilename));
                $new_file->set('type', $mime_type);
                $new_file->set('file_folder_id', $this->get('file_folder_id'));
                $new_file->set('ext', $this->get('ext'));
                if (!$new_file->save()) {
                    $this->add_error('save as new', $new_file->errors_to_string());
                    return false;
                }
                return true;                            
            } else {
                // save file
                if ( $phpThumb->GenerateThumbnail() ) 
                {
                    if ( !$phpThumb->RenderToFile($server_path_to_file.'/'.$this->get('name')) ) 
                    {
                        error_log(print_r($phpThumb->debugmessages,1));
                        flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                        return;
                    } 
                } else {
                    error_log(print_r($phpThumb->debugmessages,1));
                    flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                    return;
                }
                
                @chmod($server_path_to_file.'/'.$this->get('name'), 0755);
            }
            
            return true;
        }
        
        function resize_image($options)
        {
            // jpg fix
            $mime_type = $this->get('type');
            $jpegs = array('image/jpeg','image/jpg','image/pjpeg');
            if(in_array($mime_type, $jpegs)){
                $mime_type = 'image/jpeg';   
            }
            
            // path to file will return with a / in the front fyi
            $file_folders = new File_Folders();
            $path_to_file = path_to_file($this->get('file_folder_id'));  
            $server_path_to_file = $file_folders->get_server_path($this->get('file_folder_id'));
               
            // create php thumb instance and get jiggy with it.
            require VENDOR .'/phpthumb/phpthumb.class.php';
            $phpThumb = new phpThumb();
            $phpThumb->setSourceFilename($server_path_to_file.'/'.$this->get('name'));
        
            // set output type
            $phpThumb->config_output_format = str_replace('image/','',$mime_type);
            $phpThumb->aoe = 1; // allow output enlargement
            $phpThumb->w = (int) $options['r_width'];
            $phpThumb->h = (int) $options['r_height'];
            $newW        = (int) $options['r_width'];
            $newH        = (int) $options['r_height'];
            $file_name_action = 'resize';
            
            // save file as a new file, then input into db
            if(isset($options['save_as_new'])){
                // create a new filename
                $ext         = $this->get('ext');
                $rawname     = strtolower(substr($this->get('name'), 0, strrpos($this->get('name'), '.')));
                $rawname     = preg_replace('/[^\w.-]/', '_',$rawname); // make safe
                $uniqid      = uniqid("_{$newW}x{$newH}_");
                $newfilename = "{$rawname}_{$file_name_action}{$uniqid}.{$ext}";                    
                if ($phpThumb->GenerateThumbnail()) {
                    if (!$phpThumb->RenderToFile($server_path_to_file.'/'.$newfilename)) {
                        error_log(print_r($phpThumb->debugmessages,1));
                        flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                        return false;
                    }
                } else {
                    error_log(print_r($phpThumb->debugmessages,1));
                    flash('error','There was a fatal error in the image processing, please view the error logs for the output');
                    return false;
                }
                @chmod($server_path_to_file.'/'.$newfilename, 0755);
            
                // insert into db 
                $new_file = new Files();
                $new_file->is_file_upload = false;
                $new_file->set('name', $newfilename);
                $new_file->set('size', filesize($server_path_to_file . '/'. $newfilename));
                $new_file->set('type', $mime_type);
                $new_file->set('file_folder_id', $this->get('file_folder_id'));
                $new_file->set('ext', $this->get('ext'));
                if (!$new_file->save()) {
                    $this->add_error('save as new', $new_file->errors_to_string());
                    return false;
                }
                return true;                            
            } else {
                // save file
                if ( $phpThumb->GenerateThumbnail() ) 
                {
                    if ( !$phpThumb->RenderToFile($server_path_to_file.'/'.$this->get('name')) ) 
                    {
                        error_log(print_r($phpThumb->debugmessages,1));
                        flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                        return;
                    } 
                } else {
                    error_log(print_r($phpThumb->debugmessages,1));
                    flash('error', 'There was a fatal error in the image processing, please view the error logs for the output');
                    return;
                }
                
                @chmod($server_path_to_file.'/'.$this->get('name'), 0755);
            }
            return true;
        }
        
    }

?>